package com.leetcode.p0;

import com.bean.TreeNode;
import com.utils.TreeUtils;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的中序遍历
 * stack
 */
public class Test94_stack {

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        help(res, root, stack);
        return res;
    }

    private void help(List<Integer> res, TreeNode root, Deque<TreeNode> stack) {
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.offer(root);
                root = root.left;
            }

            root = stack.pollLast();
            res.add(root.val);

            root = root.right;
        }
    }

    public static void main(String[] args) {
        TreeNode root = TreeUtils.buildTree4();
        TreeUtils.showTree(root);

        Test94_stack test = new Test94_stack();
        List result = test.inorderTraversal(root);
        System.out.println(result);
    }

}
